/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.transitionseverywhere;


import com.transitionseverywhere.utils.RectF;
import com.transitionseverywhere.utils.ViewUtils;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorGroup;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.render.Canvas;
import ohos.agp.render.Texture;
import ohos.agp.utils.Matrix;
import ohos.media.image.PixelMap;
import ohos.media.image.common.ImageInfo;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import static ohos.agp.render.Texture.ColorType.UNKNOWN_COLORTYPE;


/**
 * Static utility methods for Transitions.
 */

public class TransitionUtils {

    private static int MAX_IMAGE_SIZE = (1024 * 1024);

    public static Animator mergeAnimators(Animator animator1, Animator animator2) {
        if (animator1 == null) {
            return animator2;
        } else if (animator2 == null) {
            return animator1;
        } else {
            AnimatorGroup animatorSet = new AnimatorGroup();
            animatorSet.runSerially(animator1, animator2);
            return animatorSet;
        }
    }

    /**
     * Creates a View using the bitmap copy of <code>view</code>. If <code>view</code> is large,
     * the copy will use a scaled bitmap of the given view.
     *
     * @param sceneRoot The ViewGroup in which the view copy will be displayed.
     * @param view The view to create a copy of.
     * @param parent The parent of view
     */
    public static Component copyViewImage(ComponentContainer sceneRoot, Component view, Component parent) {
        Matrix matrix = new Matrix();
        matrix.translate(-parent.getPivotX(), -parent.getPivotY());
        ViewUtils.transformMatrixToGlobal(view, matrix);
        ViewUtils.transformMatrixToLocal(sceneRoot, matrix);
        RectF bounds = new RectF(0, 0, view.getWidth(), view.getHeight());
        //matrix.mapRect(bounds);
        int left = Math.round(bounds.left);
        int top = Math.round(bounds.top);
        int right = Math.round(bounds.right);
        int bottom = Math.round(bounds.bottom);

        Image copy = new Image(view.getContext());
        copy.setScaleMode(Image.ScaleMode.CLIP_CENTER);
        PixelMap bitmap = createViewBitmap(view, matrix, bounds);
        if (bitmap != null) {
            copy.setPixelMap(bitmap);
        }
        copy.setLeft(left);
        copy.setTop(top);
        copy.setRight(right);
        copy.setBottom(bottom);
        return copy;
    }

    /**
     * Creates a pixelmap of the given view, using the Matrix matrix to transform to the local
     * coordinates. <code>matrix</code> will be modified during the bitmap creation.
     *
     * <p>If the bitmap is large, it will be scaled uniformly down to at most 1MB size.</p>
     * @param view The view to create a bitmap for.
     * @param matrix The matrix converting the view local coordinates to the coordinates that
     *               the bitmap will be displayed in. <code>matrix</code> will be modified before
     *               returning.
     * @param bounds The bounds of the bitmap in the destination coordinate system (where the
     *               view should be presented. Typically, this is matrix.mapRect(viewBounds);
     * @return A bitmap of the given view or null if bounds has no width or height.
     */
    public static PixelMap createViewBitmap(Component view, Matrix matrix, RectF bounds) {
        PixelMap bitmap = null;
        int bitmapWidth = Math.round(bounds.width());
        int bitmapHeight = Math.round(bounds.height());
        if (bitmapWidth > 0 && bitmapHeight > 0) {
            float scale = Math.min(1f, ((float)MAX_IMAGE_SIZE) / (bitmapWidth * bitmapHeight));
            bitmapWidth *= scale;
            bitmapHeight *= scale;
            matrix.translate(-bounds.left, -bounds.top);
            matrix.scale(scale, scale);
            try {
                PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
                initializationOptions.size = new Size(bitmapWidth, bitmapHeight);
                initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
                bitmap = PixelMap.create(initializationOptions);
                ImageInfo imageInfo = bitmap.getImageInfo();
                Texture texture = new Texture(imageInfo.size.width,
                        imageInfo.size.height, UNKNOWN_COLORTYPE, Texture.AlphaType.UNKNOWN_ALPHATYPE);
                Canvas canvas = new Canvas(texture);
                canvas.setMatrix(matrix);
            } catch (OutOfMemoryError e) {
                // ignore
            }
        }
        return bitmap;
    }

}